/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.jabber;

import org.webos.java.base.Application;
import org.webos.java.base.ApplicationType;
import org.webos.java.base.Frame;
import org.webos.java.base.Session;
import org.webos.java.base.hsqldb.HSQLDBConnection;
import org.webos.java.base.hsqldb.migration.DBDefinition;
import org.webos.java.base.hsqldb.migration.RowDefinition;
import org.webos.java.base.hsqldb.migration.TableDefinition;
import org.webos.java.base.workspace.FrameHolder;
import org.webos.java.base.workspace.Splitter;
import org.webos.java.base.workspace.Workspace;
import org.webos.java.jabber.chat.ChatFrame;
import org.webos.java.jabber.tree.ConnectionItem;
import org.webos.java.root.Log;

/**
 *
 * @author Kostya
 */

@ApplicationType(code="jabber", jsClass="jabber.JabberApp",
name="Jabber client", version="0.1", description="Simple jabber IM messaging application", icon="jabber_icon")
public class JabberApp extends Application{

    HSQLDBConnection conn = new HSQLDBConnection("/.jabber/history", "sa", "");

    private String settingName = "jabber00";
    RosterFrame rosterFrame = null;
    Workspace workspace = null;
    FrameHolder chats = null;
    ChatFrame activeChat = null;
    String workspaceTitle = "Jabber IM client";
    boolean workspaceActive = false;

    public JabberApp(Session aSession) {
        super(aSession);
    }

    public RosterFrame getRosterFrame() {
        return rosterFrame;
    }

    public void setActiveChat(ChatFrame activeChat) {
        this.activeChat = activeChat;
    }

    public ChatFrame getActiveChat() {
        return activeChat;
    }

    @Override
    public void initialize() {
        super.initialize();
        if(getOption(settingName, null)==null){
            new SettingsDialog(this, settingName);
        }else{
            initWorkspace();
        }
    }

    void afterSettings(boolean aCancel){
        if(getOption(settingName, null)==null){
            stopApplication(null);
        }else{
            if(workspace!=null){
                //Init new settings
                showWorkspace(workspace);
                if(!aCancel)
                    rosterFrame.addConnection(settingName);
            }else
                initWorkspace();
        }
    }

    public void changeWorkspaceCaption(boolean aNewMessages){
        if(workspace!=null)
            workspace.setCaption((aNewMessages?"[*] ":"")+workspaceTitle);
        setName((aNewMessages?"[*] ":"")+"Jabber client");
    }

    private void setupDB(){
        try {
            if(!conn.isActive()){
                if(!conn.openConnection(getSession()))
                    sendError(920, "Can't initialize database");
                DBDefinition db = new DBDefinition();
                TableDefinition history = new TableDefinition("history");
                history.addRow(new RowDefinition("ID", "INTEGER", true));
                history.addRow(new RowDefinition("ACCOUNT", "VARCHAR(255)"));
                history.addRow(new RowDefinition("CONTACT", "VARCHAR(255)"));
                history.addRow(new RowDefinition("INCOMING", "BOOLEAN", "true"));
                history.addRow(new RowDefinition("MESSAGE_DATE", "TIMESTAMP"));
                history.addRow(new RowDefinition("MESSAGE", "VARCHAR(4096)"));
                db.addTable(history);
                if(!db.migrateDB(conn.getConnection())){
                    sendError(920, "Can't initialize database");
                }
            }
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
    }

    private void initWorkspace(){
//        try {
//            Connection conn = HSQLDBConnection.openConnection("/.jabber/history", "sa", "", getSession());
//            if(conn!=null){
//                Log.info(this, "Connection opened sucessfully!");
//                conn.close();
//            }
//        } catch (Throwable t) {
//            Log.error(this, "Exception thrown: " + t.getMessage());
//            t.printStackTrace();
//        }
        setupDB();
        workspace = new Workspace(this, "jabber");
        changeWorkspaceCaption(false);
        Splitter splitter = new Splitter(null, "sp0");
        splitter.setRatio(0.7);
        splitter.setVertical(true);
        workspace.setItem(splitter);
        chats = new FrameHolder(splitter, "chats");
        splitter.setLeftItem(chats);
        chats.setLocked(true);
        rosterFrame = new RosterFrame(this, workspace, settingName);
        FrameHolder fh = new FrameHolder(splitter, "roster");
        fh.addFrame(rosterFrame);
        splitter.setRightItem(fh);
        addWorkspace(workspace);
        addFrame(rosterFrame);
        showWorkspace(workspace);
    }

    public ChatFrame getChatFrame(String aID, ConnectionItem aConnectionItem, String aUserName, String aUserJID){
        try {
            for (int i = 0; i < getFramesCount(); i++) {
                Frame frame = getFrameAt(i);
                if(frame.getCode().equalsIgnoreCase(aID)){
                    //Show frame here
                    return (ChatFrame) frame;
                }
            }
            ChatFrame frame = new ChatFrame(this, workspace, aConnectionItem, aUserName, aUserJID);
            frame.setFrameHolder(chats);
            chats.addFrame(frame);
            addFrame(frame);
//            jabberApp.showFrame(frame);
            return frame;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @Override
    public void workspaceStateChanged(Workspace aWorkspace) {
        workspaceActive = aWorkspace.isSelected();
        if(!workspaceActive)
            activeChat = null;
    }

    public boolean isWorkspaceActive() {
        return workspaceActive;
    }

    public HSQLDBConnection getConn() {
        return conn;
    }

    @Override
    public void terminate() {
        conn.close();
    }

}
